package com.hjj.springboot.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjj.springboot.config.LogType;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.*;
import com.hjj.springboot.entity.BigType;
import com.hjj.springboot.service.IBigTypeService;
import com.hjj.springboot.service.ISmallTypeService;
import com.hjj.springboot.util.DateUtil;
import com.hjj.springboot.util.StringUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/bigType")
public class AdminBigTypeController {

    @Autowired
    private IBigTypeService bigTypeService;

    @Autowired
    private ISmallTypeService smallTypeService;

    @Value("${bigTypeImagesFilePath}")
    private String bigTypeImagesFilePath;

    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        String query=pageBean.getQuery().trim();
        Page<BigType> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        Page<BigType> pageResult = bigTypeService.page(page,new QueryWrapper<BigType>().like(StringUtil.isNotEmpty(query),"name",query));
        Map<String,Object> map=new HashMap<>();
        map.put("total",pageResult.getTotal());
        map.put("bigTypeList",pageResult.getRecords());
        return R.ok(map);
    }

    @SystemLogs(operation = "商品大类信息",type = LogType.UPDATE)
    @RequestMapping("/save")
    public R save(@RequestBody BigType bigType){
        if(bigType.getId()==null || bigType.getId()==-1){
            bigTypeService.save(bigType);
        }else {
            bigTypeService.saveOrUpdate(bigType);
        }
        return R.ok();
    }

    @GetMapping("/{id}")
    public R findById(@PathVariable(value = "id")Integer id){
        BigType bigType=bigTypeService.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("bigType",bigType);
        return R.ok(map);
    }

    @SystemLogs(operation = "商品大类信息",type = LogType.DELETE)
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id")Integer id) {
//        大类下如果有小类 返回报错提示
        if (smallTypeService.count(new QueryWrapper<SmallType>().eq("bigTypeId",id))>0){
            return R.error(500,"商品大类下有小类信息，不能直接删除");
        }else {
            bigTypeService.removeById(id);
            return R.ok();
        }
    }

    //    批量删除
    @SystemLogs(operation = "商品大类信息",type = LogType.BATCH_DELETE)
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        if (smallTypeService.count(new QueryWrapper<SmallType>().in("bigTypeId",ids))>0){
            return R.error(500,"商品大类下有小类信息，不能直接删除");

        }else {
            bigTypeService.removeByIds(ids);
            return R.ok();
        }
    }

//    上传商品大类图片
    @SystemLogs(operation = "商品大类图片",type = LogType.UPLODE)
    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(MultipartFile file) throws Exception {
        Map<String,Object> reultMap=new HashMap<>();
        if(!file.isEmpty()){
            String originalFilename= file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(bigTypeImagesFilePath+newFileName));
            reultMap.put("code",0);
            reultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","img/bigType/"+newFileName);
            reultMap.put("data",dataMap);
        }
        return reultMap;
    }

    //    查询大类所有数据,小类下拉框用到
    @RequestMapping("/listAll")
    public R listAll(){
        HashMap<String,Object> map=new HashMap<>();
        map.put("bigTypeList",bigTypeService.list());
        return R.ok(map);
    }

    @GetMapping("/export")
    public void export(@RequestParam(required = false) String query, HttpServletResponse response)   throws Exception {
        String queryStr=query.trim();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("商品大类信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<BigType> bigTypeList = bigTypeService.list(new QueryWrapper<BigType>().like(StringUtil.isNotEmpty(queryStr),"name",query));
        EasyExcel.write(response.getOutputStream(),BigType.class)
                .sheet("商品大类信息")
                .doWrite(bigTypeList);
    }
}
